package com.xw.controller;
import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.common.TokenHandler;
import com.xw.csrf.CsrfTokenManager;
import com.xw.dao.UserDao;
import com.xw.dao.UserTokenDao;
import com.xw.entity.User;
import com.xw.exp.ServiceException;
import com.xw.jsr303Group.RegisterGroup;
import com.xw.rep.LoginRep;
import com.xw.req.LoginReq;
import com.xw.req.UpdatePasswordReq;
import com.xw.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
 * @Description: TODO
 * @Date: 2024/12/18 16:52
 * @Version: 1.0
 * @author 86151
 */
@RestController
@RequestMapping("web")
@Api(tags = "web模块")
public class WebController {

    @Resource
    private UserService userService;

    @Resource
    private UserTokenDao userTokenDao;

    @Resource
    private UserDao userDao;

    @Resource
    private CsrfTokenManager csrfTokenManager;

    /**
     * 提供获取CSRF Token的接口
     * */

    @GetMapping("token")
    @ApiOperation("获取CSRF Token接口")
    public Result<String> getCsrfToken(HttpServletRequest request, HttpServletResponse response) {
        String tokenId = UUID.randomUUID().toString();
        String token = csrfTokenManager.generateToken();
        csrfTokenManager.storeToken(tokenId, token);
        csrfTokenManager.setTokenInCookie(response, token);

        // 使用Constants枚举中的SUCCESS来获取对应的状态码和消息，构建Result对象返回
        return new Result<>(token, Constants.SUCCESS);
    }

    @PostMapping("register")
    @ApiOperation(value = "用户注册")
    public Result<?> register(@RequestBody @Validated(RegisterGroup.class) User user) {
        Boolean register = userService.register(user);
        if (register) {
            return new Result<>(Constants.SUCCESS);
        }
        return new Result<>(Constants.ERROR,"注册失败");
    }

    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    public Result<?> login(@RequestBody @Validated LoginReq loginReq) {
        LoginRep loginRep = userService.login(loginReq);
        return new Result<>(loginRep,Constants.SUCCESS);
    }

    @GetMapping("logout")
    @ApiOperation(value = "退出登录")
    public Result<?> logout(HttpServletRequest httpServletRequest) {
        // 删除token
        userTokenDao.deleteByToken(httpServletRequest.getHeader("token"));
        return new Result<>(Constants.SUCCESS);
    }

    @GetMapping("getPersonInfo")
    @ApiOperation(value = "个人信息")
    public Result<?> getPersonInfo() {
        User userInfo = TokenHandler.getUserInfo();
        return new Result<>(userInfo,Constants.SUCCESS);
    }

    @PostMapping("updatePersonInfo")
    @ApiOperation(value = "修改个人信息")
    public Result<?> updatePersonInfo(@RequestBody User user) {
        userDao.updateById(user);
        return new Result<>(Constants.SUCCESS);
    }

    @PostMapping("updatePassword")
    @ApiOperation(value = "修改密码")
    public Result<?> updatePassword(@RequestBody @Validated UpdatePasswordReq updatePasswordReq) {
        // 检查用户是否存在
        User userQueryEmail = new User();
        userQueryEmail.setEmail(updatePasswordReq.getEmail());
        List<User> usersEmailList = userDao.selectAll(userQueryEmail);
        Optional<User> userOptional = usersEmailList.stream()
                .filter(u -> u.getEmail().equals(updatePasswordReq.getEmail()))
                .findAny();

        if (!userOptional.isPresent()) {
            throw new ServiceException(Constants.ERROR.getCode(), "找不到用户信息");
        }

        // 校验两次密码是否一致
        if (!updatePasswordReq.getPassword().equals(updatePasswordReq.getConfirmPassword())) {
            throw new ServiceException(Constants.ERROR.getCode(), "两次密码输入不一致");
        }

        // 更新用户密码（直接存储原始密码）
        User updatePassword = new User();
        updatePassword.setPassword(updatePasswordReq.getPassword());
        updatePassword.setId(userOptional.get().getId());
        userDao.updateById(updatePassword);

        return new Result<>(Constants.SUCCESS);
    }

}
